<% config_contexts = @kubernetes_cluster.config_contexts %>

<section>
  <%= form_for @kubernetes_cluster, html: { class: "form-horizontal" } do |form| %>
    <%= render 'shared/errors', object: @kubernetes_cluster %>

    <fieldset>
      <%= form.input :name, required: true %>
      <%= form.input :description %>
      <%= form.input :kritis_breakglass, as: :check_box, help: "Make all resources skip kritis" if ENV["KRITIS_BREAKGLASS_SUPPORTED"] %>

      <%= form.input :auth_method do %>
        <%= form.select :auth_method, ["context", "database"] %>
      <% end %>

      <div class="auth_via_field" data-method="context">
        <%= form.input :config_filepath, label: 'Config File path', pattern: /\A\/.*\z/, help: 'Absolute paths only' %>
        <%= form.input :config_context, label: 'Context' do %>
          <% if config_contexts.any? %>
            <% config_contexts.unshift @kubernetes_cluster.config_context unless config_contexts.include?(@kubernetes_cluster.config_context) %>
            <%= form.select :config_context, config_contexts, {}, { class: 'form-control' } %>
          <% else %>
            <%= form.text_field :config_context, class: "form-control" %>
          <% end %>
        <% end %>
      </div>

      <div class="auth_via_field" data-method="database">
        <%= form.input :api_endpoint, help: "http://foo.bar" %>
        <%= form.input :client_cert, as: :text_area, input_html: { rows: 3 } %>
        <%= form.input :client_key, as: :text_area, input_html: { rows: 3 } %>
        <%= form.input :verify_ssl, as: :check_box %>
      </div>

      <%= form.actions delete: true do %>
        <% if Samson::Hooks.active_plugin?('aws_ecr') && SamsonAwsEcr::SamsonPlugin.active? && @kubernetes_cluster.persisted? %>
          <%= link_to "Seed ECR", seed_ecr_kubernetes_cluster_path(@kubernetes_cluster), class: "btn btn-default", data: {method: :post} %>
        <% end %>
      <% end %>
    </fieldset>
  <% end %>
</section>

<% if config_contexts.any? %>
  <script>
    // When an existing config is changed, we have to allow editing the context
    // since we do not know what contexts are in the new file
    $('#kubernetes_cluster_config_filepath').one('keyup', function(){
      var context = $('#kubernetes_cluster_config_context');
      context.replaceWith('<input name="' + context.attr('name') + '" type="text" value="' + context.val() + '" class="form-control">');
    });
  </script>
<% end %>

<script>
  // show fields depending on what auth method user picks
  // - timeout so field does not get shrunk to 3px after unfolding
  setTimeout(function(){
    $("#kubernetes_cluster_auth_method").change(function(){
      var current = $(this).val();
      $(".auth_via_field[data-method=" + current + "]").show();
      $(".auth_via_field[data-method!=" + current + "]").hide();
    }).trigger("change");
  }, 0)
</script>
